You can use javascript test() method to validate name field. The test() method tests for a match in a string.
/^[A-Za-z\s]+$/.test(x) //returns true if matched, vaidates for a-z and A-Z and white space
or
/^[A-Za-z ]+$/.test(x)
Answer from Konsole on Stack OverflowYou can use javascript test() method to validate name field. The test() method tests for a match in a string.
/^[A-Za-z\s]+$/.test(x) //returns true if matched, vaidates for a-z and A-Z and white space
or
/^[A-Za-z ]+$/.test(x)
If you are building something for modern browsers, there is something very pleasurable in HTML5:
<input id="username" name="name" type="text" pattern="[a-zA-Z]{5,}" title="Minimum 5 letters" required />
Reference: HTML5 forms input types
Update 2017/01/17:
Old browsers are quite weak on the market shares nowadays. This is a good practice to use HTML5 features instead of compatibility scripts.
Videos
Can I use external libraries for name validation?
Should I capitalize the name before validating it?
Should I validate names on the client side or the server side?
Your regular expression is broken. You've escaped the closing square bracket around the character set. Try this:
else if (/[^a-zA-Z0-9\-]/.test( stringf ))
Also, there's a lot of weird clutter in there that's annoying but not fatal: How many times do you really need to call getElementById('family') in that method? Once.
if (stringf=="")
{
alert("Family name must be filled out");
return false;
}
else if (stringf.length > 35)
{
alert("Family name cannot be more than 35 characters");
return false;
}
else if (/[^a-zA-Z0-9\-]/.test( stringf ))
{
alert("Family name can only contain alphanumeric characters and hypehns(-)")
return false;
}
return true;
UPDATED:
Sorry, the problem is with your regex, i missed that, change to this its fully working:
var ck_password = /^[A-Za-z0-9-]/;
if(!ck_password.test(stringf))
{
alert("Family name can only contain alphanumeric characters and hypehns(-)")
}
Console in chrome, go to the OPTIONS in the right top coner, select TOOLS, then DEVELOPER TOOLS.
Try Below Code
VF Code
<apex:inputtext value="{!name}" id="Name"/>
<apex:commandbutton onclick="validatenamevalue();" reRender="someId"/>
Javascript
function validatenamevalue(){
var name = document.getElementById('{!$Component.formId.Name}').value;
if(name == '' || name == null) {
alert('Please enter FirstName & LastName');
} else if((name.indexOf(' ') > 0 && name.indexOf(' ') == (name.length)-1) || !(name.indexOf(' ') > 0)) {
alert('Please Enter Last Name');
}
}
You can refer the following link and modify your code accordingly - How to write Javascript validation for Visualforce page