0
votes

I have a form with 4 fields First Name (required) Last Name (required) Email (required) phone (optional) (if user enter any it should validate to a number or not) below is the form i have

<form name="myForm" method="post" onsubmit="return validate();">
First Name : <input type="text" name="fname" id="id_fname"> <br>
Last Name : <input type="text" name="lname" id="id_lname"> <br>
Email : <input type="text" name="email" id="id_email"> <br>
Phone : <input type="text" name="phone" id="id_phone"> <br>
<input type="submit" value="send">
</form>

And below is the javascript code

<script type="text/javascript">
function validate()
{
 if (document.myForm.id_fname.value == '') {
alert("Enter First Name"); 
return false;}

else if(document.myForm.id_lname.value == '') {
alert("Enter Last Name");
return false; }

// now here email validation is not working

else if(document.myForm.id_email.value == '' || document.myForm.id_email.value != ''){
var x = document.myForm.id_email.value;
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
    alert("Not a valid e-mail address");
    return false;
    else
    return true;
    } 

// this is for phone number, if this field is empty no validation, if this field not empty it should validate to contain only numbers

else if(document.myForm.id_phone != '') {
var ValidChars = "0123456789";
var IsNumber=true;
var Char;
sText = document.form1.testfield2_phone.value ;
for (i = 0; i < sText.length && IsNumber == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
}
}

if(IsNumber == false)
alert("Enter valid Number");
return false;
else
return true;
}


else
return true;
document.myForm.submit();
}
</script>

Email validation and phone validation are not working when i comment these email and phone i get validation good for first name and last name... is there any error in code for validation.

And when a form is submitted, when we refresh then details are resubmitted again, how to avoid this.

2

2 Answers

2
votes

Why do you do it so complicated???

if (document.myForm.id_fname.value.length < 3) {
    alert("Enter First Name");
    return false;
} else if (document.myForm.id_lname.value.length < 3) {
    alert("Enter Last Name");
    return false;
} else if (!/^\S+@\S+\.\w+$/.test(document.myForm.id_email.value)) {
    alert("Not a valid e-mail address");
    return false;
} else if (!/^\d+$/.test(document.myForm.id_phone.value)) {
    alert("Enter valid Number");
    return false;
}
return true;
1
votes

There are multiple syntax errors, which are mainly related to the else if

For the resubmissions have alook at Post - Redirect - Get (PRG) is a common design pattern for web developers to help avoid certain duplicate form submissions and allow user agents to behave more intuitively with bookmarks and the refresh button.