Reputation: 341
Upon clicking a submit button, I would like to do some client side validation to ensure there are fewer than 5 commas in a text box with the class of submit-btn. I can use javascript, jquery and/or regex here.
What code should I place within this function?
$('.submit-btn').on("click", function() {
<< WHAT GOES HERE? >>
});
Any help is greatly appreciated.
Upvotes: 0
Views: 1585
Reputation: 163362
You could also remove everything that is not a comma [^,]
, replace that with an empty string and count the length of the string.
$('.submit-btn').on("click", function() {
var nr = $("#tbx").val().replace(/[^,]/g, "").length;
console.log("Fewer than 5 commas? " + (nr < 5 ? "Yes" : "No") + " there are " + nr + " commas.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='tbx'>
<button class='submit-btn' type="button">Click</button>
Upvotes: 1
Reputation: 14313
I use regex to find the number of times the string ,
occurs in the textbox value. It prints whether or not it is valid (having less than 5 commas).
$("#validate").click(function () {
console.log(($("#textboxInfo").val().match(/,/g)||[]).length < 5)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textboxInfo" />
<button id="validate">less than 5 commas?</button>
In this particular situation, I'd prefer to have live validation. This can be accomplished by using the input
event.
$("#textboxInfo").on('input', function () {
var isValid = ($(this).val().match(/,/g) || []).length < 5;
$(".isValid").html(isValid ? "Valid" : "Invalid");
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textboxInfo" value="I really love ,,, commas!" />
<div class="isValid"> </div>
Upvotes: 4
Reputation: 1108
You could try using this Comma Counter
$('button').on('click',function(){
var counter = ($('div').html().match(/,/g) || []).length;
$('.result').text(counter);
}
)
/
Upvotes: 1
Reputation: 50316
Split
the value of the input box and filter
out ,
and check the length of it
$('.submit-btn').on("click", function() {
var getNumbers = $('#testBox').val().split('').filter(function(item) {
return item === ','
}).length;
console.log(getNumbers)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='testBox'>
<button class='submit-btn' type="button">Click</button>
Upvotes: 3