Regular expression to check only alphabets - javascript

I am trying to achieve form validation of only alphabets but this regular expression doesnt seem to work
function check() {
var reg="/^[a-zA-Z]*$/";
var x = document.forms['frm'].name.value;
var y= document.forms['frm'].email.value;
if( x === ""){
alert('Name field cant be empty');
$("#nameone").focus();
return false;
}
else if (!reg.match(x)){
alert('NAME must contain alphabets only');
return false;
}
else if( y === ""){
alert('Email field cant be empty');
$("#emailone").focus();
return false;
}
else {
return true;
}
}
this is my form ,i have added the details ,the input fields
<form class="reg_form" name='frm' method="post" onsubmit='return check();' >
<div class="input-field col-md-4">
<input type="text" placeholder="1. Name" name="name" id='nameone'/>
</div>
<div class="input-field col-md-4">
<input type="text" placeholder="2. Email" name="email" id='emailone' />
</div>
<div class="input-field col-md-4 ">
<input type="text" placeholder="3. phone" name="phone" />
</div>
</form>

In this case, your code isn't working 'cause your regex was set as a string in the line:
var reg="/^[a-zA-Z]*$/";
The regex was suposed to be set without quotes:
var reg=/^[a-zA-Z]*$/;
I suggest that instead of the method 'match', you use:
else if (!reg.test(x)){
This is more performatic and return a boolean value.

Instead of...
var reg = "/^[a-zA-Z]*$/"; // produces a **string**
You should omit the surrounding quotes:
var reg = /^[a-zA-Z]*$/; // produces a **Regex object**
The second uses javascript inline Regex syntax, with the slashes functioning as delimiters.
Furthermore you can use the simple .test() function to check if a string conforms to a Regex or not.
Demo:
var reg = /^[a-zA-Z]*$/;
console.log(reg.test("ABcd"));
console.log(reg.test("123"));

you can use
string.match("^[a-zA-Z]+$$");
you will get true if the string contains only letters and false otherwise

Related

How to match password and confirm password with regex validation for uppercase and number

I want to match password and confirm password also do the regex validation for minimum 8 chars,Atleast 1 capital char, And atleast 1 number, i have done code so far, in console regex matching is giving null.
Thanks in Advance
var pass = $("#password").val();
var cpass = $("#cnfpassword").val();
var passformat = "/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8})$/";
console.log(pass, cpass);
console.log(passformat.match(pass));
if (passformat.match(pass)) {
console.log(pass.match(passformat));
if (pass == cpass) {
document.getElementById('alertmsg').innerHTML = "Password Matched!";
// return true;
} else {
document.getElementById('alertmsg').innerHTML = "Password Did not match!";
// return false;
}
} else {
document.getElementById('alertmsg').innerHTML = "password must be at least 8 characters contain capital letters,and number!!!";
// return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group mt-2">
<input type="password" class="form-control" id="password" aria-describedby="password" placeholder="Enter a password" style="width: 80%; margin: auto;" required onkeyup="ValidatePassword()">
</div>
<div class="form-group mt-2">
<input type="password" class="form-control" id="cnfpassword" aria-describedby="cnfpassword" placeholder="Repeat your password" style="width: 80%; margin: auto;" required onkeyup="ValidatePassword()">
</div>
Regex for min 8 characters and contain at least 1 UPPERCASE, 1 lower case, 1 number, 1 special character
const myRegEx = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})");
myRegEx.test(password)
You usage of .match() should be the other way round. It should run as follows:
console.log( pass.match( passformat ) )
See MDN for more info.
Also, you're regex is in a string, which may not be picked up correctly. Try the regex without the quotes, like below:
var passformat = /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8})$/;

JS Student Email Validation

I am a beginner in Javascript and am looking to find a solution to why the code below is not working.
I've reviewed several tutorials here on StackOverflow and believe it should work... but it's not.
The HTML looks like this:
<form id="personalInfo">
<h2>Email: </h2>
<input type="text" name="Email" id="Email">
<br>
</form>
<input type="button" onclick = "validateEmail()">
The Javascript looks like this:
function validateEmail()
{
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
var address = document.forms[personalInfo].elements[Email].value;
if (reg.test(address) == false) {
alert ("Email not valid");
return false;
}
return true;
}
By my accounts, this should pop up an alert if the email address entered by the user is not valid.
Instead, nothing happens at all. I'm not sure if the test is even run.
function validateEmail() {
// There are, I feel, better version of this regex online
// You can check "https://emailregex.com/"
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
// document.getElementById() - Easier to read & understand, and more widely used
var address = document.getElementById('Email').value;
// Corrected your returns - not the main issue in the function, but the old
// returns might have caused confusion
if (reg.test(address) == false) {
alert("Email not valid");
return false
}
return true
}
<form id="personalInfo">
<h2>Email: </h2>
<input type="text" name="Email" id="Email">
</form>
<!-- You had a typo on the onclick but has since been fixed -->
<input type="button" onclick="validateEmail()" value="Submit">
Two issues here:
1- In your HTML, you are missing an = sign here: onclick"validateEmail()" (Edit: seems you fixed it now)
2- in your Javascript, the indices personalInfo and Email are strings, wrap them in quotation marks:
var address = document.forms['personalInfo'].elements['Email'].value;
function validateEmail()
{
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
var address = document.forms['personalInfo'].elements['Email'].value;
if (reg.test(address)== false)
{
alert ("Email not valid");
return false
}
return true;
}
<form id="personalInfo">
<h2>Email: </h2> <input type="text" name="Email" id="Email"> <br>
</form>
<input type="button" onclick="validateEmail()">
When dealing with email inputs, set the input type to email instead of text - like so:
<input name="my-email" type="email" />"
Then the browser will perform validation on the input; such as if the input doesn't have the # present.

Password validator with 8 characters and 2 digits don't work

Hey i'm trying to make this password validator working with 8 characters and 2 digits but.. it doesn't.
I don't see how there's something wrong about my code .My console doesn't say that there's an error
<div class="field with-indicator">
<label for="pass-one">Password:</label>
<input type="text" name="pass-one" id="pass-one" />
<span id="validity" class="indicator">Not Ok</span>
</div>
<script>
let input = document.getElementById('pass-one');
let regex = new RegExp("^(?=(.*[a-zA-Z]){1,})(?=(.*[0-9]){2,}).{8}$");
if ( !regex.test(input))
{
document.getElementById("validity").innerHTML = "Not Ok";
//return false;
}
else
{
document.getElementById("validity").innerHTML = "Ok";
}
</script>
In order to make your code work you need to wrap it into an event handler. For instance you may use the change event and the addEventListener() to set the handler:
document.getElementById('pass-one').addEventListener('change', function(e) {
let regex = new RegExp("^(?=(.*[a-zA-Z]){1,})(?=(.*[0-9]){2,}).{8}$");
if ( !regex.test(this.value)) {
document.getElementById("validity").innerHTML = "Not Ok";
//return false;
} else {
document.getElementById("validity").innerHTML = "Ok";
}
})
<div class="field with-indicator">
<label for="pass-one">Password:</label>
<input type="text" name="pass-one" id="pass-one" />
<span id="validity" class="indicator">Not Ok</span>
</div>
Try to make validation e.g. after each input changes oninput="validPass()" (I not change your regexp but add wrapper validPass() function and event in you <input> tag in snippet below - but if you wanna passwort to be at least 8 characters or longer then change last part in regexp .{8}$ to .{8,}$)
let input = document.getElementById('pass-one');
let regex = new RegExp("^(?=(.*[a-zA-Z]){1,})(?=(.*[0-9]){2,}).{8}$");
function validPass() {
if ( !regex.test(input.value))
{
document.getElementById("validity").innerHTML = "Not Ok";
}
else
{
document.getElementById("validity").innerHTML = "Ok";
}
}
<div class="field with-indicator">
<label for="pass-one">Password:</label>
<input type="text" name="pass-one" id="pass-one" oninput="validPass()" />
<span id="validity" class="indicator" >Not Ok</span>
</div>

jquery.validatior.addMethod valid pattern with a space for email

I need to check email text before save it.
I want to fill in multiple email and seperate by ";" with following formats:
without a space "nicola#gmail.com;linda#gmail.com" (I succeed)
with a space "nicola#gmail.com; linda#gmail.com"
with mutiple spaces "nicola#gmail.com;    linda#gmail.com"
And I cannot use type "email" because Edge don't support, so I back to use a standard "text" input.
$.validator.addMethod("pattern", function(value, element, param) {
if (this.optional(element)) {
return true;
}
if (typeof param === "string") {
param = new RegExp(param);
}
return param.test(value);
}, "Invalid format");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<div class="form-data-field">
<label class="fld">email</label>
<input class="content" type="text" name="email" data-formfield="Email" maxlength="150"
pattern="^(([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$|^NC$" />
</div>
I add \s* after [;] in pattern, and it works well
pattern="^(([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;]\s*(([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$|^NC$"

NIC and username validation field

I have two fields, the NIC and the username. Their validation are
NIC check for numbers or characters
username field must contain more than 8 characters including the date
of birth from the NIC.
So far I tried this for my NIC.
function validateNIC()
{
var nic = document.getElementById('NIC');
var mesg = document.getElementById('message1');
if (NIC.length != 14) {
message1.innerHTML="Length must be 14 characters";
} else{
message1.innerHTML="Length is good";
}
}
<div class="form-group">
<label for="username"><span class="req">* </span> NIC NUMBER:</label>
<input class="form-control" type="text" name="NIC" id = "NIC" required onkeyup = "validateNIC();" maxlength=14 />
<span id="message1"></span>
</div>
And for my username I tried this.
function Validate(txt) {
txt.value = txt.value.replace(/[^a-zA-Z-'\n\r.]+/g, '');
}
<div class="form-group">
<label for="username"><span class="req">* </span> User name:</label>
<input class="form-control" type="text" name="username" id="txt" onkeyup="Validate(this)" maxlength=14 required />
<div id="errLast"></div>
</div>
My validation for the NIC is not quite working.It keeps showing
"Length must be 14 characters" even if the length is good.
And for the username part, can anyone tell me how to do it ? Is
there an array I must do or something ? An example of the NIC is
T2108974302906 where 210897 is the DOB.
var nic = document.getElementById('NIC');
var mesg = document.getElementById('message1');
if (NIC.length != 14) {
Here NIC refers to the DOM element, not the value of that input element.
You want to use nic.value.length.
As for the username, your RegEx looks strange [^a-zA-Z-'\n\r.]. This set matches characters that are not in the set. Why did you put \n and \r?
Anyway, if you are using a <form> element to submit these field, I suggest you use pattern attribute. You can test yoru patterns on http://regex101.com/
To extract the DOB:
<input pattern="^T[0-3]\d[0-1]\d{10}$">
validateNIC() {
var nic = document.getElementById('NIC');
var isValid = /^T[0-3]\d[0-1]\d{10}$/.test(nic.value);
var dob = nic.value.substring(1, 7);
}
var nic = document.getElementById('NIC');
This statements gets the input element - not its value. You need to get its value as such:
var nic = document.getElementById('NIC').value;
Then, you can compare the length to 14. I would also suggest using !== instead of !=.
Username validation - why are you replacing the value if you're trying to validate? And why is your max value 14 and not 8?

Categories

Resources