jquery validations :i want to reset validations when i press reset button - jquery-validate

<script type="text/javascript">
/* <![CDATA[ */
jQuery(function(){
jQuery("#ValidNumber").validate({
expression: "if (!isNaN(VAL) && VAL) return true; else return false;",
message: "Should be a number"
});
jQuery("#Email").validate({
expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\#[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
message: "Should be a valid Email id"
});
jQuery("#ValidNumber").validate({
expression: "if (VAL > 100) return true; else return false;",
message: "Should be greater than 100"
});
jQuery("#Mobile").validate({
expression: "if (VAL.match(/^[9][0-9]{9}$/)) return true; else return false;",
message: "Should be a valid Mobile Number"
});
});
/* ]]> */
</script>
actually this is my script for jquery coming to my question how can i reset the validations along with the text fields when i press the reset button in a form whats the procedure involved in it.

When you bundle your validation code into one validate call like this:
window.validator = $('form#your_formid').validate({
rules: {
validNumber: {
expression: "if (!isNaN(VAL) && VAL) return true; else return false;"
},
email: {
required: true,
email: true
},
// ...
},
messages: {
validNumber: {
expression: 'Should be a number'
},
email: {
required: 'Fill in your email,
email: 'Valid email please'
}
}
You can call resetForm on de validate object when you click the reset button
window.validator.resetForm();

Related

Confirmation delete data using sweetAlert with laravel 6

I'm trying to create delete confirmation in my app using sweet alert when I click to delete button so I am facing an error on console Uncaught TypeError: Cannot call a class as a function
Please suggest on how to fix this error?
Controller
public function destroy($id)
{
$delete = Digitizing::where('id', $id)->delete();
if ( $delete == 1) {
$success = true;
$message = "User deleted successfully";
} else {
$success = true;
$message = "User not found";
}
}
HTML view
<a class="btn btn-danger" onclick="deleteConfirmation({{$digitizing-
>id}})">Delete</a>
<script type="text/javascript">
function deleteConfirmation(id) {
swal({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-
token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
</script>
It's because of the swal({ part of your code.
Swal is the name of the class. You will want to replace it with Swal.fire(.
Additionaly, please note that your php code will return $success = true; in both scenarios. You might want tot update that as well.

Knockout JS validation message repeating twice

New to Knockoutjs, Just trying to fix an existing bug in validation message. Below mentioned extend validation messages repeating twice in the UI.
$.each(viewModel.Form.Questions(), function () {
var currentQuestion = this;
debugger;
$.each(currentQuestion.QuestionAnswers(), function () {
var text = this.AnswerDisplay();
this.AnswerValue.extend({
required: {
message: text + " : Question price is required",
onlyIf: function () {
return viewModel.Form.FormPrice.PricingMode() == 2;
}
},
min: {
message: text + " : Question price should be a number",
onlyIf: function () {
return viewModel.SelectedQuestion() != null && currentQuestion.FormQuestionId() == viewModel.SelectedQuestion().FormQuestionId() && viewModel.Form.FormPrice.PricingMode() == 2;
},
params: 0
}
});
});
});

unable to view ajax response in chrome dev tools

I'm trying to view the AJAX response in Chrome DevTools. However, I'm greeted with, "the request has no response data available." Am I doing something wrong?
Here's the request (I'm always greeted with the "response false" alert, even if it's a valid email address. Hence, my trying to troubleshoot. However, I'll leave that for another question):
$("#email_address").on("keyup", function() {
request = $.ajax({
url: 'verify_email.php',
data: {email: $("#email_address").val(),
submitted: true},
type: 'post'
});
request.done(function(response) {
if(response == true) {
alert("response true");
} else if(response == false) {
alert("response false");
} else {
alert("heh?");
}
});
request.error(function(response) {
alert("an error occurred");
});
});
Here's my verify_email.php code that's called with the AJAX request, if it helps at all:
<?php
if(isset($_POST['submitted']) and isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
?>
Try:
<?php
if(isset($_POST['submitted']) && isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo 'true';
return true;
} else {
echo 'false';
return false;
}
}
?>
I've never used and in an if() myself (does it work?). Probably not your problem though ...
You're not echoing anything onto the page so you're return a page that's got no response data to show.

Backbonejs collection.create: how to prevent it from adding items if there is an error?

How can I prevent collection.create from adding items into its collection if there is an error found in the input?
html,
<div id="new-status">
<h2>New monolog</h2>
<form action="">
<textarea name="content"></textarea><br>
<input type="submit" value="Post">
</form>
</div>
<div id="statuses">
<h2>Monologs</h2>
<ul></ul>
</div>
backbone,
var Status = Backbone.Model.extend({
initialize: function(){
},
validate: function(attrs, options) {
if(attrs.text === '') alert("please enter some text");
},
url:"dummy.php",
sync: function (method, model, options) {
return $.ajax({
type: "POST",
dataType: 'json',
url: 'server.php',
data: {
text: this.get("text")
}
});
}
});
var Statuses = Backbone.Collection.extend({
model: Status
});
var NewStatusView = Backbone.View.extend({
events: {
"submit form": "addStatus"
},
initialize: function(options) {
_.bindAll(this, 'addStatus', 'clearInput');
this.listenTo(this.collection, 'add', this.clearInput) ;
},
addStatus: function(e) {
e.preventDefault();
this.collection.create({ text: this.$('textarea').val() });
},
clearInput: function() {
this.$('textarea').val('');
}
});
var StatusesView = Backbone.View.extend({
initialize: function(options) {
this.collection.on("add", this.appendStatus, this);
},
appendStatus: function(status) {
this.$('ul').append('<li>' + status.escape("text") + '</li>');
}
});
$(document).ready(function() {
var statuses = new Statuses();
new NewStatusView({ el: $('#new-status'), collection: statuses });
new StatusesView({ el: $('#statuses'), collection: statuses });
});
So, when you hit the submit button without typing any text, you get an error popup from this part in the model,
validate: function(attrs, options) {
if(attrs.text === '') alert("please enter some text");
},
But how can I tell the collection that there is an error and do not add this empty item and also do not fire sync in the model?
EDIT:
got it worked with collection.create in this way...
model,
validate: function(attrs, options) {
if(attrs.text === '') {
var message = "please enter some text";
alert(message);
return message;
}
},
view,
addStatus: function(e) {
e.preventDefault();
var one = new Status({ text: this.$('textarea').val() });
if (!one.isValid()) {
alert(one.validationError);
} else {
this.collection.create(one);
}
},
it seems to work fine unless it is not a good approach or against MVC pattern?
I don't think collection.create is the right choice here.
addStatus: function(e) {
e.preventDefault();
var status = new Status({"text": this.$('textarea').val()})
var error = status.valiate();
if(!error) {
this.collection.add(status);
}
},
Also not that the backbone docs says this about validate:
If the attributes are valid, don't return anything from validate; if
they are invalid, return an error of your choosing. It can be as
simple as a string error message to be displayed, or a complete error
object that describes the error programmatically.
So, your validate function should be fixed:
validate: function(attrs, options) {
if(attrs.text === '') {
var message = "please enter some text";
alert(message);
return message;
}
},
Your Model's validate method should return an error string so that models save is not fired in case of alert.
validate: function(attrs, options) {
if(attrs.text === ''){
alert("please enter some text");
return "Text is empty."; // OR proper error CODE
}
}
Check validate method of Backbone.Model.

using jquery to validate postal code based on country

Working on site where we currently accept US zip codes. I already have jquery validate working for that. What i want to do now is add a drop down for the user to select country, and then based on the country they selected, it will validate the postal code to make sure it matches.
Can someone give me some pointers on how i can do this? Basically, i just need to change the regex the validator function is using based on the country drop down. The (what i assume is) relevant section of the jquery validator function is this:
(function ($) {
$.fn.validate = function (options) {
var defaults = {
invalidClass: 'error',
rules: {
req: /.{1,}/g,
email: /[\w\.=-]+#[\w\.-]+\.[\w]{2,3}/g,
phone: /\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})/g,
zip: /\d{5}$|^\d{5}-\d{4}/g,
//password: /^(?=.*\d)(?=.*[a-zA-Z]).{8,20}$/g,
password: /^(?=.{8,20}$)(?=.*\d)(?=.*[a-zA-Z]).*/g,
//nospecialchars: /[^<>?,\/\\\[\]\{\}\|!##$%^&*()_+;:"]{1,}/g
nospecialchars: /^(?!.*[?<>;]).+$/g
},
error_messages: {
req: 'Oops..',
email: 'Please enter your email address.',
phone: '',
zip: 'Please give me a valid zip.',
max: 'too many characters.',
password: '',
nospecialchars: ''
},
success: null,
failure: null
},
errors = [],
opts = $.extend(true, defaults, options);
return this.each(function () {
var $this = $(this);
$(this).find('input[type="submit"]:not(.cancel), button').click(function () {
errors = [];
validate_fields($this);
if ($this.find('.error').length === 0) {
if (typeof opts.success == 'function')
return opts.success();
}
else {
if (typeof opts.failure == 'function')
return opts.failure(errors);
}
});
});
I'm not very familiar with jquery so i don't know what the syntax is here for me to create an if-else or case statement to set the regex.
Thanks if advance for any help.
edit: Here's the bit of code that actually calls the validation
<script type="text/javascript">
$(function () {
setForm();
$('form').validate({
error_messages: {
req: null
},
failure: function (errors) {
var sel = '';
$(".errMsg").hide();
for (x in errors) {
sel += ',#' + errors[x][0];
}
if (sel.length > 0) {
sel = sel.substring(1);
$(sel).parent().find(".errMsg").show(0, function () {
$('#home .orange_box, #home .HomeRight').height('auto');
$('#infov .white_box, #infov .orangeRight').height('auto');
$('#findt .orange_box, #findt .HomeRight').height('auto');
if ($.browser.msie && $.browser.version == 8) {
evenColumns('#home .orange_box', '#home .HomeRight', -16);
evenColumns('#infov .white_box', '#infov .orangeRight', -16);
evenColumns('#findt .orange_box', '#findt .HomeRight', -16);
}
else {
evenColumns('#home .orange_box', '#home .HomeRight', -15);
evenColumns('#infov .white_box', '#infoforv .orangeRight', -15);
evenColumns('#findt .orange_box', '#findt .HomeRight', -15);
}
});
}
return false;
},
success: function () {
$(".errMsg").hide();
return true;
}
});
I would create an object, witch has:
function for the validation
object for all other countries
object for default rules
validation = {
validate : function( sCountryName, sToValidate ){
return ( null != sToValidate.match( this.countries[ sCountryName ] ? this.countries[ sCountryName ].zip : this.defaultRules.zip ))
},
countries : {
england : {
zip : /\d{5}$|^\d{5}-\d{4}/g
}
},
defaultRules : {
zip : /\d{5}$|^\d{5}-\d{4}/g
}
}

Resources