how to use regexp to validate form input javascript - javascript

I'm beginner at using JavaScript, and I have read documentation of RegExp and went trough couple of examples but I can't to figure it out how to use it properly.
I have a form which contains 5 input fields. I need to use RegExp to validate user input into form. The forbidden values are
( ) { } ' ! # “ \ /
Other characters are allowed but before submitting a form all input field must be entered (no blank/empty fields are allowed).
Input field id="unos_naziv_proizvoda" must contain at least 5 characters and start with capital letter.
Input field id="unos_opis_proizvoda" must contain at least 3 sentences. Sentence starts with a capital letter and end with a dot.
Input field id="unos_datum_proizvodnje" which is date of manufacturing must be in form of dd.mm.yyyy, can't be in the future (must be lower or same as today) and must be type text
Here is HTML code:
<form id="forma_prijava" class="forma_novi_proizvod" action="http://barka.foi.hr/WebDiP/2016/materijali/zadace/ispis_forme.php" method="POST">
<label for="unos_naziv_proizvoda">Naziv proizvoda</label>
<input type="text" name="naziv_proizvoda[15]" id="unos_naziv_proizvoda" placeholder="Unesite naziv proizvoda" maxlength="15">
<label for="unos_opis_proizvoda">Opis proizvoda</label>
<textarea name="opis_proizvoda" id="unos_opis_proizvoda" placeholder="Ovdje unesite opis proizvoda" rows="50" cols="100"></textarea>
<label for="unos_datum_proizvodnje">Datum proizvodnje</label>
<input type="date" name="datum_proizvodnje" id="unos_datum_proizvodnje">
<label for="unos_vrijeme_proizvodnje">Vrijeme proizvodnje</label>
<input type="time" name="vrijeme_proizvodnje" id="unos_vrijeme_proizvodnje">
<label for="unos_kolicina_proizvodnje">Količina proizvodnje</label>
<input type="number" name="kolicina_proizvodnje" id="unos_kolicina_proizvodnje" placeholder="Unesite količinu proizvodnje" min="1">
<button type="Submit" value="Submit">Dodaj proizvod</button>
<button type="Reset" value="Reset">Poništi unos</button>
</form>
Here is js code:
window.onload = function(){
var provjeri = function(){
var re = new RegExp(/[^(){}'!#"\/]/, g);
var uzorak = document.getElementById("forma_prijava"); //id of a form //
var ok = re.test(uzorak.value);
if(!ok){
alert("Niste unijeli valjani tekst"); //alert message if it's not valid input //
return false;
}
else{
alert("OK"); // message if it's valid input //
return true;
}
};
document.getElementById("forma_prijava").addEventListener("oninput", provjeri);
};
I don't know should I use it on a whole form as one unit or on each input field separately because I have different types of input fields (two are text and others are date, time and number). If someone could provide more understandable explanation when providing an example I would appreciate that. :)
Just to point it out once again, I strictly must use RegExp (pure JavaScript), no other libraries or frameworks do not come in mind!
Thank you in advance!

You can use property pattern of the input Tag
<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">

Related

Client side input validation via Bootstrap and jQuery

I am kind of stuck, with this I don't even know where to start but
I need to mark the first input as green on the correct password, red if the password does not meet the requirements
Requirements:
Passwords must be at least 10 characters long and have lowercase and uppercase letters
Passwords less than 15 characters must have a number and a special character
Marking the second input outline as green if it matches the first input and the password is correct, red otherwise.
Any help would be very appriciated
<div class="form-group">
<label for="newPasswordTextBox">Password</label>
<input type="password" id="newPasswordTextBox" class="form-control" name="newPassword"
placeholder="New Password" autocomplete="off">
</div>
<div class="form-group">
<label for="confirmNewPasswordTextBox">Confirm Password</label>
<input type="password" id="confirmNewPasswordTextBox" class="form-control"
name="confirmNewPassword" placeholder="Confirm New Password" autocomplete="off">
</div>
<div class="small">
<ul>
<li>Passwords must be at least 10 characters long and have a lowercase and
uppercase letters</li>
<li>Passwords less than 15 characters must have a number and a special
character</li>
</ul>
</div>
You could try using javascript to collect both inputs document.getElementById("newPasswordTextBox") and document.getElementById("confirmNewPasswordTextBox") and then you can take the .value attributes from the input boxes to check the input against if conditionals with your specified requirements. eg.
let newPass=document.getElementById("newPasswordTextBox");
newPass.addEventListener("keyup",function(evt){
let val=newPass.value;
//check requirements here
});
or in jquery
$("#newPasswordTextBox").on("keyup", function(evt){
let val=$("#newPasswordTextBox").val(); //get the value using jquery
//check requirements here
});
Next, use if conditionals by //check requirements here to get your functionality. You can use val.length to get the length of the string obtained from the textbox, then just compare this to the size you want(10). Repeat the aforementioned for 15 but just add the extra requirements of checking for numbers and special characters(see regular expressions in javascript). For validating that passwords match just grab both values and use "===" to determine if they are equal. You can also change the input boxes' outline colours using the border property as follows:
$("#newPasswordTextBox").css({"border-color":"green"});//Use the appropriate id and colour for the box you wish to change
Addition(correcting the authors code post):
I've managed to capture most of what I believe you'd want here and corrected some of your code by changing the wrong variables that were called and changed to the proper regex code.
$("#newPasswordTextBox").on("keyup", function () {
let pass = $("#newPasswordTextBox").val();
if ((pass.length >=10) && (pass.length < 15)) {
var regex = /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[ `!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~])/;
if(!pass.match(regex)){
$("#newPasswordTextBox").css({ "border-color": "red"});
}
else{
$("#newPasswordTextBox").css({ "border-color": "green" });
}
} else if (pass.length>=15){
$("#newPasswordTextBox").css({ "border-color": "green","outline":"none" });
}else {
$("#newPasswordTextBox").css({ "border-color": "red","outline":"none" });
}
}
);
$("#confirmNewPasswordTextBox").on("keyup", function () {
let pass = $("#confirmNewPasswordTextBox").val();
let confpass = $("#newPasswordTextBox").val();
if (pass === confpass) {
$("#confirmNewPasswordTextBox").css({ "border-color": "green","outline":"none" })
} else {
$("#confirmNewPasswordTextBox").css({ "border-color": "red","outline":"none" });
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<body>
<input type="text" id="newPasswordTextBox" placeholder="new">
<input type="text" id="confirmNewPasswordTextBox" placeholder="re-enter">
</body>

jQuery Click Function, input value length and pattern

I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.

Prevent unallowed pasting into text-input

I'm trying to prevent the user from pasting unallowed text into an input field. The Input is a randomly generated 8 digit Code, that contains letters and numbers.
But I don't want the user to paste any text that contains other characters.
my input field:
<input type='text' id='form-code-field' name='code' maxlength='8'>
Note:
I'm not looking for something like the readonly attribute, because the user still has to input alphanumeric text into the field.
You could test value input using a regex on input event:
$('#form-code-field').on('input', function(){
if(!/^[a-z0-9]+$/i.test(this.value)) this.value = $(this).data('oldValue') || "";
else $(this).data('oldValue', this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' id='form-code-field' name='code' maxlength='8'>
For HTML5 browsers you can also do this, and no script required:
<input type='text' name='code' maxlength='8' pattern="^[a-z0-9]+$" title="a-z0-9">
This will not stop someone from write non valid characters, the pattern will be evaluated on submit and will abort the submit with a message if not matched.
Update
I added a plain javascript version for those who don't use jQuery, which works globally on a form. Just set the "pattern" on a input field and it kicks in.
The script also works on input on non HTML5 browsers.
A "safety" note:
As a client side evaluation, this by no means is 100% safe to just store server side, you always need to check whats posted before doing anything with it.
document.getElementById('form').addEventListener('input', function(e){
if (e.target.pattern && e.target.pattern.length > 0) {
var regex = new RegExp(e.target.pattern,"i");
if(!regex.test(e.target.value)) {
if (e.target.value.length > 0) {
e.target.value = e.target.getAttribute('data-old-value') || "";
} else {
e.target.setAttribute('data-old-value', "");
}
} else {
e.target.setAttribute('data-old-value', e.target.value);
}
}
}, false);
<form id="form">
Only alphanum (max 8): <input type='text' id='form-code-field' name='code' maxlength='8' pattern="^[a-z0-9]+$" title="a-z0-9"><br /><br />
Any character (max 5): <input type='text' id='form-code-field' name='code' maxlength='5' ><br />
</form>

JavaScript string is not a function

When working on a page whenever I call on my second function, validateNumber(), I get a "typeError: String is not a function" message can anyone explain to me why this message is occuring? My code is as follows:
< script type = "text/javascript" >
/* <![CDATA[ */
function validateLetter(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
dataEntry.value = replacedInput;
} catch (textInputError) {
window.alert(textInputError)
return false;
}
return true;
}
function validateNumber(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if (textInput != replacedInput)
throw "You can only enter numbers into this field.";
} catch (numberInputError) {
window.alert(numberInputError)
return false;
}
return true;
}
function validateInput(dataEntry) {
if (navigator.appName == "Microsoft INternet Explorer")
var enteredKey = dataEntry.keyCode;
else if (navigator.appName == "Netscape")
var eneteredKey = dataEntry.charCode;
}
/* ]] */
< /script>
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded" name="dataEntry">
<p>Enter your mother's maiden name:
<input type="text" id="letter1" name="letter1" onkeypress="validateLetter(this)">
</p>
<p>Enter the city you were born in:
<input type="text" id="letter2" name="letter2" onkeypress="validateLetter(this)">
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter3" name="letter3" onkeypress="validateLetter(this)">
</p>
<p>Enter your phone number:
<input type="text" id="number1" name="number1" onkeypress="validateNumber(this)">
</p>
<p>Enter the year you were born:
<input type="text" id="number2" name="number2" onkeypress="validateNumber(this)">
</p>
<p>Enter the number of siblings you have:
<input type="text" id="number3" name="number3" onkeypress="validateNumber(this)">
</p>
<p>
<button type="reset" value="Reset Form">Reset Form</button>
</p>
</form>
I am almost certain this is the problem:
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if textInput is a string you cannot pass parameters to it as if it were a function, instead:
var replacedInput = textInput.replace(/[^0-9]/g, ""); // dependening in what you are trying to achieve of course
var replacedInput = textInput(/[^0-9]/g);
That's not how you do search and replace in Javascript.
It's not quite clear what you intended here, but if you wanted to remove non-digits from the string, you'd do that using String.replace():
var replacedInput = textInput.replace(/[^0-9]/g, "");
That being said, an easier way of accomplishing this check would be to skip the replacement entirely and just use String.match() instead:
var textInput = dataEntry.value;
if (textInput.match(/[^0-9]/))
throw "You can only enter letters into this field.";
dataEntry.value = textInput;
You might consider isolating functionality so that functions like validateLetter simply validate that the string they are passed contains only letters, then have the caller function work out what to do if the return value is true or not.
In that case, you end up with very much simpler functions:
function validateLetters(s) {
return /^[a-z]+$/i.test(s);
}
function validateNumbers(s) {
return /^\d+$/.test(s);
}
To validate an input, you can add a class to say what type of validation it should have, e.g.
<input name="letter3" class="letter" onkeypress="validateLetter(this)">
Then the validateInput function can determine which validation function to call based on the class:
function validateInput(element) {
var value = element.value;
// If has class letter, validate is only letters
if (/(\s|^)letter(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateLetters(value) && value != '') {
alert('Please enter only letters');
}
}
// If has class number, validate is only numbers
if (/(\s|^)number(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateNumbers(element.value) && value != '') {
alert('Please enter only numbers');
}
}
}
Note that keypress is not a good event to use for validation as data can be entered without pressing any keys (e.g. paste from the context menu or drag and drop). Also, the listener doesn't see the value resulting from the keypress, it sees the previous value.
You really only need to perform validation when the form is submitted. Until then, why do you care what the values are? Allow the user to make mistakes and fix them themselves without being pestered by alerts (onscreen hints are really useful). Spend some time using your forms to enhance their usability (I realise this is probably not a production form, but names can have characters other than the letters a to z, e.g. von Braun and O'Reilly).
Lastly, form controls rarely need an ID, the name is usually sufficient to identify them if required (and they must have a name to be successful, so most have a name already). A bit of play HTML from the OP:
<form>
<p>Enter your mother's maiden name:
<input name="letter1" class="letter" onkeypress="validateInput(this)">
</p>
<p>Enter the number of siblings you have:
<input name="number3" class="number" onkeypress="validateInput(this)">
</p>
<p>
<input type="reset">
</p>
</form>

i want to use onblur to validate alpha and hyphen for textbox in form

I want to use javascript to validate using onblur if the user is inputting only alpha values and hyphen in the textbox.
*First Name: <input type="text" name="fn" onblur="alphahyphen()"/> <br />
*Family Name: <input type="text" name="sn" onblur="alphahyphen()"/><br />
function alphahyphen(){
var letters = /^[a-z A-Z\-]+$/;
if(task3.fn.value.match(letters)){
return;
}else{
alert("Enter alpha");
}
}
I dont want it to show an error message when the field is left empty as i am using an onsubmit for that.
Any help?

Categories