Regex for 2 Upper case Alphabet followed by 3 numbers - javascript

I'm new to regex and facing issue in below problem statement.
Problem statement : What I need is a text box where the content must start with 2 upper case alphabets and follows by 3 digits. This textbox can be empty.
function validateModuleCode()
{
var m = document.getElementById("moduleCode").value;
if (/^[A-Z]{2}[0-9]{3}$/.test(m) == false)
{
document.getElementById("moduleError").innerHTML = "Invalid";
return false;
}
else
{
document.getElementById("moduleError").innerHTML = "";
return true;
}
}
Module Code:
<br/>
<input type = "text" id = "moduleCode" name = "module code" onkeypress = "validateModuleCode()">
<span style = "color:red" id = "moduleError"></span>
<br/><br/>
However, the moduleError keeps popping out and shows invalid even though I have entered a valid value. Here is the error image.
How do I correct this ?

You can use oninput event to get the updated input value. Also, You have to add a check for the empty value. So that it should be valid if there is no value in the text box.
Live Demo :
function validateModuleCode() {
var m = document.getElementById("moduleCode").value;
if (m && (/^[A-Z]{2}[0-9]{3}$/.test(m) === false)) {
document.getElementById("moduleError").innerHTML = "Invalid";
return false;
} else {
document.getElementById("moduleError").innerHTML = "";
return true;
}
}
<input type="text" id="moduleCode" name="module code" oninput="validateModuleCode()">
<span style="color:red" id="moduleError"></span>

Related

How to add more than 2 conditions in an If/Else statement in Javascript?

Me again.
So I have been working on this basic search functionality where I am comparing the value entered as text with a list of other values and doing an action based on it.
In simpler words. I am making a search where the logic compares the value with other strings and if the comparison is successful then show and hide and vice versa if the condition is false.
Now the other condition i want to implement is that when the text bar(where the user will enter the value) is empty then both the divs should be shown. Below is my code for this:
HTML where I am getting the value from: - Im using the onchange to get the value - oninput is not working :(
<label>Find your location:</label>
<input type="text" class="form-control" id="search_input" placeholder="Type address..."
onChange="myFunction()"/>
And This is my JS code
<script>
function myFunction() {
var inzone = document.getElementById("inzone");
var outzone = document.getElementById("outzone");
if(document.getElementById("search_input").value == null
||document.getElementById("search_input").value == "")
{
outzone.style.display = "";
inzone.style.display = "";
}
else if (document.getElementById("search_input").value === 'something something')
{
outzone.style.display = "none";
inzone.style.display = "";
}
else {
inzone.style.display = "none";
outzone.style.display = "";
}
document.getElementById("search_input").value == null will never be true. The value property of an HTMLInputElement is always a string. It may be "", but not null or undefined (the two things == null checks).

How to allow only numbers between 0 to 30 or A,D character in input using javascript?

Hi i have created a javascript function to only allow numbers between 0 to 30 and character A and D. I give an alert if it does not match the criteria but if the user clicks ok on the alert the values still remain in the input and can be updated in the database. I want that user should not be able to enter anything at all in the input box except character A , D and numbers between 0 to 30 like it is done in the case of input type=number we can only enter numbers. My javascript function is:-
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
The javascript works fine with validation but after clicking ok in alert value still remains there and it also gives error when input box is empty any way to avoid that. Is there any other better way to create the function or can it done by using jquery. I am new to jquery if it is possible to do it with jquery it would be great. I would be highly gratefull if anybody can help.
You may try this code example.
function validate(box) {
var val = box.value;
if (!/^[AD]?$/.test(val) && isNaN(val) || (0 > val || 30 < val)) {
box.value = '';
alert('Only A or D or 0-30');
}
}
<input type='text' value='30' onblur='validate(this);' />
The best solution would be to check it at the moment when you are inserting it in the database.
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
If you want to make sure there is no error when the text is empty, you can do this. The .replace part is to ensure that if the text input is filled with only spaces, it is considered empty.
With the rest of the function:
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
How about replacing disallowed values so only the desired input is allowed. With this you won't be able to enter anything other than A, D and numbers 0 - 30:
$('input').on('input', function(e) {
this.value = this.value
.replace(/[^AD\d]/, '')
.replace(/(3)[1-9]/, '$1')
.replace(/(30)[0-9]/, '$1')
.replace(/([4-9])[0-9]/, '$1')
.replace(/([\d][\d])[\d]/, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" />
Note, it's still a good idea to do some server side validation.

condtion in javascript validation not working properly

I have a textbox and a submit button
<input type="text" name="username" id="username"/><br/>
<input type="submit" onclick="return validate()"/>
Here is the function code:
if (document.getElementById("usernameee").value == null || document.getElementById("usernameee").value == "" ) {
document.getElementById("usernameee").style.borderColor = 'red';
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
if (document.getElementById("usernameee").value.length!=0 || document.getElementById("usernameee").value.length < 8 ) {
document.getElementById("usernameee").style.borderColor = 'red';
document.getElementById("message").innerHTML="Enter Atleast 8 Characters"
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
}
now what is want is that if the user leaves the filed empty it should only highlight the textbox with backgound color red and if the username is less than 8 characters it should show the message and highlight the backgound of textbox but now even if the textbox is empty it is displaying the message which i dont want...if the field is empty it should ol
I think your second conditional is wrong. Also you can write the code much cleaner like this:
var username = document.getElementById("usernameee");
if(!username.value) {
//There is no username
username.style.borderColor = 'red';
} else if(username.value.length < 8) {
//There is a username and the value is shorter than 8 characters
username.style.borderColor = 'red';
document.getElementById("message").innerHTML = "Enter Atleast 8 Characters";
} else {
//There is a username and it is longer than or equal to 8 characters.
username.style.borderColor = '';
document.getElementById("message").innerHTML = "";
}

How to add a validation error message next to a field using jQuery

Hi have a form with a few fields. Amongst them:
<div>
<label for="phoneNumber" class="label">Phone Number</label>
<input name="phoneNumber" type="text" id="phoneNumber" size="13" style="float:left;margin-right:10px;">
</div>
<div>
<input type="checkbox" name="activePN" id="activePN" checked >
<label for="activePN">Active</label>
</div>
The, when the form is submited, I want to validate the input and write next to each field for whichever field didn't validate. Like this:
$('#submit').click(function () {
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
if (strippedPN.length !== 10) {
$('#phoneNumber').text('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
...
...
...
});
I was hopping that adding those <p> </p> tags would do it. But they don't...
Note: I also tried with html() instead of text() and with activePN instead of phoneNumber.
Use .after().
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
It might be wise to add a class to your p tag too, so you can remove them when the number is edited to be correct.
Try:
$('#submit').click(function(){
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, ''); //strips non-digits from the string - already a String
if(strippedPN.length !== 10){
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
}
Its best to use jqueryvalidation plugin.
But in some scenario may be you need to show validation message using custom code, then below may help.
Code
var errorSeen = false;
$('#txtname').keyup(function (e) {
var validInput = false; // TODO set your validation here
if (!validInput) {
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorSeen === false && errorMessageVisible === false) {
$('#txtname').style.borderColor = "red";
$('#txtname').after("<span class='validationMessage' style='color:red;'>
Name is required.</span>");
errorSeen = true;
}
}
else {
$('#txtname').style.borderColor = "";
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorMessageVisible)
$(".validationMessage").remove();
errorSeen = false;
}
});

checking space between text in javascript

I want to check the gap between two or more words, i have given as an input, in a text box. If there had any space, then i want to alert user that no space is allowing. I can check the existence of text simply using "if else" statement. But can't do the desired stuff in this way. My code is given below :
<script type="text/javascript">
function checkForm()
{
var cName=document.getElementById("cName").value;
var cEmail=document.getElementById("cEmail").value;
if(cName.length<1)
{
alert("Please enter both informations");
return false;
}
if(cEmail.length<1)
{
alert("Please enter your email");
return false;
}
else
{
return true;
}
}
Name : <input type="text" id="cName" name="cName"/>
<br/>
<br/>
Email : <input type="text" id="cEmail" name="cEmail"/>
<br/>
<br/>
<input type="submit" value="Go!"/>
</form>
Thankyou
Just use the match() method of strings. For example:
'Spaces here'.match(' ');
That returns true.
'Nospace'.match(' ');
That returns false.
So for what you want, just use something like this:
if(cName.match(' ')){
alert('Spaces found!');
return false;
}
Demo
your question not very clear , but i hope you want to count your words you can use the following code to split a text and by using the length property you count the word
var b = document.getElementById("cName").value;
var temp = new Array();
temp = b.split(' ');
var count= temp.length;
and if you want to validate your name field that should not use any space
if ( ^[A-Za-z]$.test(document.getElementById("cName").value) ) {
// your code;
}
if ( document.getElementById("cName").value.indexOf(' ') > 0 ) {
alert('space found');
}

Categories

Resources