How to validate 10 digit mobile number and text in name area in php contact us form

I am new to php,so I am trying to make contact us form with all validations.I am not able to achieve it for mobile and Name column. I tried it as below

var Mobile=document.getElementById(‘mob’).value;
if(Mobile==“” || Mobile==null || Mobile==‘Mobile No.(required)’)
{
alert('Please enter your Mobile ');
document.getElementById(‘mob’).focus();
return false;
}
// to validate Mobile Number should be a 10 digit numeric value
var Mobile=document.getElementById(‘mob’).value;
var phone=“/[1][0-9]*$/”;
if(!preg_match(phone,Mobile))
{
alert(“Not a valid Mobile Number”);
document.getElementById(‘mob’).focus();
return false;
}

But it’s not working.Could anyone suggest how can I achieve it for both Mobile and name


  1. 1-9 ↩︎

Hi vivek_pandey welcome to the forum

First and foremost, trying to run JavaScript code as PHP code won’t work very well.

What error messages did you get?

In any case you should never rely on javascript for validating data. You’re best of using ajax to send it to PHP then have PHP validate the data

1 Like

I did not get any particular error but by putting above code it does not validate mobile number and accepting whatever I put there.

This is my first line in

and in function allfields() I put code for validation.

Could you please suggest where should I use javascript and any sample code snippet. I would like to make sure until visitor provide valid name,email and mobile number he should not submit form.

Thanks!

Thank You Mate. I am novice to it. I am creating a simple website to learn it step by step.

How can I do that

Start with the PHP validation, then add the HTML validation - use the pattern attribute (at that point you will likely find no use for JavaScript validation as PHP covers it for your purposes and HTML reports problems to the person filling out the form before they submit it rather than them having to wait to see the errors from the PHP.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.