I am trying to check whether or not a certain string contains only A-Z, hyphen, apostrophes and accents (e.g. umlauts, etc).
I have the following but it is not working.
var lastNameValidation = /^[a-zA-ZàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ]$/;
var customerFullName = (inputData.customerName).replace(/\s/g, "");
if (!(customerFullName.matches(lastNameValidation))) {
inputValidation += 'Invalid characters in first or last name. Only alphabetic letters, apostrophe, accents and hypen characters allowed<br/>';
}
I have removed whitespace from customerFullName and it appears to work correctly (I used an alert box to check)
I have tried both .matches and .test, but neither seem to work for me!
What am I doing wrong?
Change your regex to
var lastNameValidation = /^[a-zA-ZàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ]+$/i
and use .match() . .matches() is not for string regex matching.
http://www.w3schools.com/jsref/jsref_match.asp
var check = function() {
var lastNameValidation = /^[a-zA-ZàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ]+$/i
var custname = document.querySelector("#name").value;
var customerFullName = custname.replace(/\s/g, "");
if (!(customerFullName.match(lastNameValidation))) {
alert('Invalid characters in first or last name. Only alphabetic letters, apostrophe, accents and hypen characters allowed<br/>');
} else {
alert("perfect")
}
}
<input id="name">
<input type="button" value="check" onclick="check()">