Javascript input validation - javascript

How do I ensure that there are no special characters in the name except an apostrophe...Eg:- I can allow O'Connor but not John "Doe" ? Please help.

Use a regular expression, if you want only English characters with an apostrophe use ^[A-Za-z\']*$ you can extend this to check for a LOT of things. Regular Expressions are a very powerful tool and I'd advise reading up on them(they exist in pretty much every programming language)
var validRegex = /^[A-Za-z\']*$/;
if(myString.search(validRegex)==-1)
alert("Error");
Edit: added example.

Here's a working example of how you'd use a regular expression to check for a valid name given the conditions you laid out:
<!DOCTYPE html>
<html>
<head>
<title>Check for a good name</title>
<script>
var goodName = /^[A-Za-z'\s]+$/;
function checkName(name){
if (goodName.test(name)) {
alert("Name is great!");
} else {
alert("Name contains illegal characters");
}
}
</script>
</head>
<body>
<form onsubmit="return false;">
<input type="text" name="name" size="20">
<input type="button" value="Check"
onclick="checkName(this.form.name.value);">
</form>
</body>
</html>
The /^[A-Za-z'\s]+$/ regular expression allows uppercase English, lowercase English, apostrophes, and spaces. (It's similar to the one proposed by Afiefh, with the addition of the \s to allow spaces, and the + instead of the * to prevent blank names from passing the test.)
As David Dorward suggests above, if you really are using this to test names, you might consider relaxing the rule to accommodate international names by changing line 6 to this:
var goodName = /^([ \u00c0-\u01ffa-zA-Z'\-])+$/;
This allows unicode characters, apostrophes, and hyphens.

Related

Regex not recognizing input value for vehicle license plate

I'm having a problem with my regex validation code. I'm trying to figure out how can I validate a vehicle license plate number. The code that I wrote is listed below this message. This is written down in React inline code and I've written down two different regex expressions and both of the come out to be false. The license plate number should be in this format XX-NNNN-XX.
X = Letter
N = Number
const [licencePlate, setLicencePlate] = useState('');
var ValidateLicencePlate = /^[A-Z][A-Z]-[0-9][0-9][0-9][0-9]-[A-Z][A-Z]$/g ;
var regex = /^[A-Z]{2}-[0-9]{4}-[A-Z]{2}$/g ;
<input name="licence-plate" type="text" className="feedback-input" maxLength='10' onChange={(e) => setLicencePlate(e.target.value.toUpperCase())} placeholder="XX-NNNN-XX"/>
This regex can solve the problem.
let regex = /^[A-Z]{2}-\d{4}-[A-Z]{2}/gi
This regex will match two alphabet at the beginning, four digits at the middle and two alphabet at the end.
You can use regex as following
<input pattern="/^[A-Z]{2}-\d{4}-[A-Z]{2}/g"/>
You can put your regex in the pattern attribute of the input element. I do not see you are using regexps yo have defined anywhere in your listing.
<input pattern={regex}/>
If you have a regex constraint to validate against it may be better and more comfortable to use Constraint Validation API.
<input pattern="your regex here"/>
Browser already validates everything in form elements if you constraint them with various ways like patter attribute and unless you tell it not to validate. But still I see many code bases trying to do the validation themselves. It is unnecessary since there is a way platform itself supports and does itself.

Remove special character of substring only by Regular Expression

<html lang="en">
;;;;;;
<body>
<script>
var a = 3;
var b = a * 10;
</script>
</body>
</html>
This is is content of a string variable of my project.
And I want to remove ; of javascript code, not remove ; above the <body>
Only remove ; between <script> and </script>
Is it possible by Regular Expression?
The purpose to do this is that I want to remove unnecessary characters of string, and the string can include javascript and other language.
But as you know javascript allow semicolons and no-semicolons.
Short answer
You can try Regex lookbehind. Working example
Problem - Less Browser support
Long answer
You can use Regex capturing group to search for the semicolon which needs to be removed using the following pattern:
/(<script>[\S\s]*);(?=[\s\S]*<\/script>)/g
And then, you can use String.replace() method to remove the semicolon. Working example

Convert working UK Phone Number JS RegExp to HTML Pattern RegExp [duplicate]

.*(\d{3}\-\d{3}\-\d{2}\-\d{2}|\d{3}\-\d{2}\-\d{2}\-\d{3}|\d{10}).* this pattern was working fine. But suddenly it stop working in chrome and opera lately. What's going on here ? What a problem is here and how it's wrong? Opera is informing about invalid escape, same in chrome. It works fine when im checking it in js.
<form>
<input type="text" pattern=".*(\d{3}\-\d{3}\-\d{2}\-\d{2}|\d{3}\-\d{2}\-\d{2}\-\d{3}|\d{10}).*">
<button>
Send
</button>
</form>
The point is that Chrome and Firefox already support ES6 regex specifications and support the Unicode mode by default.
Unicode patterns have stricter rules as to what characters can be escaped inside the pattern. See this reference:
IdentityEscape: In BMP patterns, many characters can be prefixed with a backslash and are interpreted as themselves (for example: if \u is not followed by four hexadecimal digits, it is interpreted as u). In Unicode patterns that only works for the following characters (which frees up \u for Unicode code point escapes): ^ $ \ . * + ? ( ) [ ] { } |
The same set of chars is referred to as SyntaxCharacter in the ES6 specs page.
So, you can only escape the - inside the character class where it is considered a special character and to make it a literal you can escape it. Everywhere else it must not be escaped.
<form>
<input type="text" pattern=".*(\d{3}-\d{3}-\d{2}-\d{2}|\d{3}-\d{2}-\d{2}-\d{3}|\d{10}).*">
<input type=Submit>
</form>
Try to use below concept to implement to validate the date format
<form onsubmit="alert('Submitted.');return false;"><input required="" pattern="(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}" value="" name="dates_pattern0" id="dates_pattern0" list="dates_pattern0_datalist" placeholder="Try it out." type="text"><input value="ยป" type="submit"></form>
you can find more validations by this link - http://html5pattern.com/Dates

Textbox to accept only one #

I'm creating an email field in my html, can I only accept one #?
For example email:
chong!#$#gmail.com - should invalid because of there are others special characters included
or
ch#ng#gmail.com - should also be invalid because there are two #'s.
The only accepted special character should only be one #, how do I do this in javascript/jquery?
Sorry I really don't know much in regex. Or is there another way to validate an email format?
You can use the following regex in your input:
<input type="email" pattern="[a-zA-Z0-9.]+\#[a-zA-Z0-9.]+\.[a-zA-Z]+" />
This pattern avoid the user input an 'email' that don't fits with the email standard but also avoid limited the number of characters input in the name of user to 64 characters and the number of characters in the domain too.
^[A-Z0-9._%+-]{1,64}#(?:[A-Z0-9-]{1,63}.){1,125}[A-Z]{2,63}$
Some other patterns for validate numbers, numbers and letters and just letters:
^[0-9]+$
^[a-zA-Z0-9]+$
^[a-zA-Z]+$
Also you can use regular expression with javascript like this
Validate email address in JavaScript? and this other page its really useful for check if your regex pattern works correctly
http://regexr.com/
Try using this. It will open up a popup explaining the error if format is incorrect:
<form>
<input pattern="[a-zA-Z0-9.]+\#[a-zA-Z0-9.]+\.[a-zA-Z]+" title="Write your error here" />
<input type="submit" />
</form>
Hope this helps.

What did I do wrong here? [Javascript Regex]

So I am writing a registration form and I need the display name to be only numbers, letters and underscores.
Have a look at my code and tell me what I'm doing wrong.
<form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<input type="submit" />
</form>
<script type="text/javascript">
<!--
var name_regex = /^([a-zA-Z0-9_])+/
function check_form()
{
if (!name_regex.test(document.forms[0].elements[0].value))
{
document.forms[0].elements[0].focus()
alert("Your display name may only contain letters, numbers and underscores")
return false
}
}
-->
</script>
It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work.
Your regex
/^([a-zA-Z0-9_])+/
Looks for
Start of string(check), followed by
1 or more letters, numbers, or underscore (check)
And then whatever comes after it doesn't matter. This regex will match anything at all so long as it begins with a letter, number, or underscore
If you put a $ at the end, then it will work - $ matches 'end of string', so the only way it can match is if there are only numbers, letters, and underscores between the start and end of the string.
/^([a-zA-Z0-9_])+$/
Secondly, I'd suggest using document.getElementById('display-name').value instead of document.forms as it won't break if you rearrange the HTML, and is more 'the commonly accepted standard of what to do'
My regexp would go along the lines of: /^[a-zA-Z0-9_]+$/
edit: I think it's the lack of a line end $ that makes it fail.
What does "doesn't work" mean? Does it reject valid display names? Does it accept invalid display names? Which ones?
Per #Annan, leaving off the $ would make the regexp accept invalid display names like abc123!##.
If the code is rejecting valid display names, it may be because the parentheses are being matched literally instead of denoting a group (I'm not sure of the quoting convention in JS).
A simpler way to write it still would be
var name_regex = /^([a-z0-9_])+$/i;
Even simpler:
var name_regex = /^\w+$/;
I tested your script and meddled with the javascript. This seem to work:
<form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<input type="submit" />
</form>
<script type="text/javascript">
<!--
var name_regex = /^([a-zA-Z0-9_])+$/;
function check_form()
{
if (!name_regex.test(document.forms[0].elements[0].value))
{
document.forms[0].elements[0].focus();
alert("Your display name may only contain letters, numbers and underscores");
return false;
}
}
-->
</script>
Sorry guys I should have been more specific. Whenever I added spaces the values were still being accepted. The dollar sign $ did the trick!
By 'not working' I take it you mean it is letting invalid entries through (rather than not letting valid entries through).
As #Annan has said, this would probably be due to the lack of the $ character at the end of the expression, as currently it only requires a single valid character at the start of the value, and the rest can be anything.

Categories