How to hide error message in vue js after validation is true? - vue.js

Actually my problem I am checking when a particular value is valid through v-on:input. If, the value is invalid I get the response as "invalid data" and i display the same. But, when the value becomes valid, the "invalid data" is not hiding. How to I able to do so.
My code is
methods: {
checkLimit: function () {
var vm = this;
data = {};
if (this.no != '') data['no'] = this.no;
$.ajax({
url: "doc/checkNumber",
method: "POST",
data: data,
dataType: "JSON",
success: function (e) {
if (e.status == true) {
}
else{
console.log(e.msg);
vm.error = e.msg;
}
},
});
},
}
So if status is false, I am showing as
<input type="text" class="form-control" v-model="orno" required=""
v-on:input="checkLimit" maxlength="3"><p>{{error}}</p>
But when Status is true the error message is still present. How can I update based on the change?

You should set the error to '' when the e.status is true. Like this
success: function (e) {
if (e.status == true) {
vm.error = '';
} else {
console.log(e.msg);
vm.error = e.msg;
}
},

Simple: in checkLimit do vm.error=null on success. Then in the template do <p v-if="error">{{error}}</p>.
Since in vue all data is reactive p will disappear when error is falsy.
EDIT: if you want to keep the p and toggle the message do as suggested in the other comment (no v-if).

Related

Vue VeeValidate - How to handle exception is custom validation

I have a custom validation in VeeValidate for EU Vat Numbers. It connects to our API, which routes it to the VIES webservice. This webservice is very unstable though, and a lot of errors occur, which results in a 500 response. Right now, I return false when an error has occured, but I was wondering if there was a way to warn the user that something went wrong instead of saying the value is invalid?
Validator.extend('vat', {
getMessage: field => 'The ' + field + ' is invalid.',
validate: async (value) => {
let countryCode = value.substr(0, 2)
let number = value.substr(2, value.length - 2)
try {
const {status, data} = await axios.post('/api/euvat', {countryCode: countryCode, vatNumber: number})
return status === 200 ? data.success : false
} catch (e) {
return false
}
},
}, {immediate: false})
EDIT: Changed code with try-catch.
You can use:
try {
your logic
}
catch(error) {
warn user if API brokes (and maybe inform them to try again)
}
finally {
this is optional (you can for example turn of your loader here)
}
In your case try catch finally block would go into validate method
OK, first of all I don't think that informing user about broken API in a form validation error message is a good idea :-| (I'd use snackbar or something like that ;) )
any way, maybe this will help you out:
I imagine you are extending your form validation in created hook so maybe getting message conditionaly to variable would work. Try this:
created() {
+ let errorOccured = false;
Validator.extend('vat', {
- getMessage: field => 'The ' + field + ' is invalid.',
+ getMessage: field => errorOccured ? `Trouble with API` : `The ${field} is invalid.`,
validate: async (value) => {
let countryCode = value.substr(0, 2)
let number = value.substr(2, value.length - 2)
const {status, data} = await axios.post('/api/euvat', {countryCode: countryCode, vatNumber: number})
+ errorOccured = status !== 200;
return status === 200 ? data.success : false;
},
}, {immediate: false})
}
After searching a lot, I found the best approach to do this. You just have to return an object instead of a boolean with these values:
{
valid: false,
data: { message: 'Some error occured.' }
}
It will override the default message. If you want to return an object with the default message, you can just set the data value to undefined.
Here is a veeValidate v3 version for this:
import { extend } from 'vee-validate';
extend('vat', async function(value) {
const {status, data} = await axios.post('/api/validate-vat', {vat: value})
if (status === 200 && data.valid) {
return true;
}
return 'The {_field_} field must be a valid vat number';
});
This assumes your API Endpoint is returning json: { valid: true } or { valid: false }

Update the notification counter in mvc 4

I want to sync the notification counter on both sides at a time. The attached image will make you understand easily what i need to do on which I am stuck from quite a few days.
Image:
The Right Side of the notification bell is in Layout:
<div class="header-top">
<h2 style="width:100%">#ViewBag.Heading</h2>
<a class="info sprite" id="lnkInfo"></a>
#{
if(ViewBag.ShowNotification != null && ViewBag.ShowNotification) {
<span class="notifications-icon"><em>#ViewBag.NotificationCount</em></span>
}
}
</div>
The Left Notification Bell is in View.
Code:
<div class="head">
<span class="notifications-icon"><em>#Model.Announcement.Count</em></span>
<h3>Notifications</h3>
</div>
Jquery Ajax Call to Controller Action:
function UpdateNotification(id) {
var json = { "AnnouncementID": id };
$.ajax({
type: 'POST',
url: '#Url.Action("UpdateNotificationData", "Home")',
contentType: 'application/json; charset=utf-8',
data: '{"AnnouncementID":' + id + '}',
dataType: 'json',
cache: false,
success: function (data) {
if (data) {
updatenotificationUI(id);
}
}
})
}
function updatenotificationUI(id) {
var $notificaitonContainer = $(".notifications");
if (id != null) {
var $li = $notificaitonContainer.find("li[id=" + id + "]");
if ($li != null) {
$li.slideUp("slow", function () {
$(this).remove();
var legth = $notificaitonContainer.find("#listing li").length;
if (legth > 0)
$notificaitonContainer.find("em").html(legth);
else
$notificaitonContainer.find("em").html("");
});
}
}
else {
$notificaitonContainer.find("ul").html("");
$notificaitonContainer.find("em").html("");
}
}
Home Controller :
public ActionResult UpdateNotificationData(string AnnouncementID)
{
var announcements = new AnnouncementResponse() { Announcement = new List<Announcement>() };
if (IsUserAuthenticated)
return RedirectToAction("Index", "Account");
announcements = _contentManager.Announcement();
var item = announcements.Announcement.Where(p => p.AnnouncementID == Convert.ToInt32(AnnouncementID)).FirstOrDefault();
announcements.Announcement.Remove(item);
ViewBag.NotificationCount = announcements.Announcement.Count;
return Json(new { success = true });
}
But the Notification Bell in Layout doesnt update with the viewbag value or even when the model is assigned to it.
Please provide a solution for this.
You're only updating one of the two notifications. First you find a containing element:
var $notificaitonContainer = $(".notifications");
The HTML in the question doesn't have any elements which match this, so I can't be more specific. But just based on the naming alone it sounds like you're assuming there's only one such container.
Regardless, you then choose exactly one element to update:
var $li = $notificaitonContainer.find("li[id=" + id + "]");
(This can't be more than one element, since id values need to be unique.)
So... On your page you have two "notification" elements. You're updating one of them. The solution, then, would be to also update the other one. However you identify that elements in the HTML (jQuery has many options for identifying an element or set of elements), your updatenotificationUI function simply needs to update both.

x-editable price format issue

i have an issue in x-editable plugin, how to display prices in correct format in x-editable ? i would like to get the values as in price format like xx,xxx.xx ?
My code is
var editVehiclePrice = function (el, options) {
var options = $.extend(true, {
url: Utils.siteUrl() + 'dashboard/sell_vehicle/inline_vehicle_edit/',
ajaxOptions: {
dataType: 'json'
},
mode: 'inline',
}, options || {
params: function(params) {
params.veh_id = $(this).data('vehid');
return params;
},
success: function(response, newValue) {
if(response.status == 0) return response.msg;
console.log(Utils.numberFormat(newValue,2));
$(response.to_update).text(newValue);
},
validate: function(value) {
if($.trim(value) == '') {
return 'This field is required';
}
}
});
$(el).editable(options);
}
That console.log will display correct format value..but when i update it displays number in normal format.. Please help me
if we want to display any changes after editing, we should add
display: function(value, response) {
var k = Utils.numberFormat(value,2);
$(this).text(k);
},
The price will display in the number format.
Just to add to Anju's reply, Utils.numberFormat(value,2); is not defined. you can replace that with number.toFixed(2).replace(/(\d)(?=(\d{3})+.)/g, '$1,'); or wrap it into a utility function

MVC4 .Net , controls on hidden fields

I wonder if it's possible to have controls (dataanotation) on hidden fields (HiddenFor or hidden EditorFor) ?
I don't think so, but we never know.
There are a lot of posts on how to hide EditorFor such as :
TextBoxFor vs EditorFor, and htmlAttributes vs additionalViewData
In my case,in a view I have a jquery call to a WCF REST service, that in success case fill my EditorFor. I would like that the Required DataAnotation to be applied on that EditorFor, would it be possible ?
I think that as long as the EditorFor is invisible the DataAnotation cannot be applied. Would it have a way to apply the DataAnotation on the hidden EditorFor ?
Here is the code :
To hide the EditorFor :
#Html.EditorFor(model => model.VilleDepart, "CustomEditor", new {style = "display:none;" })
The CustomEditor :
#{
string s = "";
if (ViewData["style"] != null) {
// The ViewData["name"] is the name of the property in the addtionalViewData...
s = ViewData["style"].ToString();
}
}
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { style = s })
the model :
string _VilleDepart;
[Required]
[Display(Name = "Ville Départ")]
public string VilleDepart
{
get
{
if (Commune != null) {
return Commune.Commune1;
}
return _VilleDepart;
}
set {
_VilleDepart = value;
}
}
The JQuery call to WCF REST Service :
$(document).ready(function () {
$([document.getElementById("IVilleDepart"), document.getElementById("IVilleArrivee")]).autocomplete({
source: function (request, response) {
$.ajax({
cache: false,
type: "GET",
async: false,
dataType: "json",
url: GetSearchCommunetURl + "(" + request.term + ")",
success: function (data) {
//alert(data);
response($.map(data, function (item) {
return {
label: item['Commune'] + ' (' + item['CodePostal'] + ')',
val: item
}
}))
},
error: function (response) {
alert("error ==>" + response.statusText);
},
failure: function (response) {
alert("failure ==>" + response.responseText);
}
});
},
select: function (e, i) {
if (e.target.id == "IVilleDepart") {
VilleDepart = i.item.val;
EVilleDepart.value = VilleDepart.Commune;
ECodePostalDepart.value = VilleDepart.CodePostal;
ECodeINSEEDepart.value = VilleDepart.CodeINSEE;
}
if (e.target.id == "IVilleArrivee") {
VilleArrivee = i.item.val;
EVilleArrivee.value = VilleArrivee.Commune;
ECodePostalArrivee.value = VilleArrivee.CodePostal;
ECodeINSEEArrivee.value = VilleArrivee.CodeINSEE;
}
},
minLength: 2
});
});
If I don't hide the EditorFor I can see it is correctly filled after the WCF REST service call and the Required DataAnotation is applied.
There are other way to hide the EditorFor, for instance to apply the style='width:0px;height:0px'
It hides but disable the Required DataAnotation,
if I apply the style='width:0px;height:1px', we don't see a lot of the EditorFor but the Required DataAnotation is active.
I've seen an answer at http://www.campusmvp.net/blog/validation-of-hidden-fields-at-the-client-in-asp-net-mvc
(but it seems i had badly searched precedently, the validation of hidden field is treated in some blogs and sites).
To active the validation of hidden fields, you just have to add this little javascript line :
$.validator.setDefaults({ ignore: null });
and it works !
Apparently it doesn't work with mvc2, but works since mvc3.

extract text from dojo xhrPost

I have a function in which I am doing a dojo.xhrPost(). Now the returning data is wrapped in an unwanted <div> which is framework specific and cannot be removed. How can I strip away the div element. Here is my code.
function sendForm() {
var resultNode = dojo.create("li");
dojo.xhrPost({
url: "${sectionaddurl}",
form: dojo.byId("sectionform"),
load: function(newContent) {
dojo.style(resultNode,"display","block");
resultNode.innerHTML = newContent;
},
error: function() {
resultNode.innerHTML = "Your form could not be sent.";
}
});
$("#sectionform")[0].reset();
dojo.place(resultNode, "existing_coursesection", "first");
}
In jquery we would do $("#some_ID").text(); where the id will be the div obtained via ajax.
Will dojo allow me to manipulate the request data which is like <div id="unwanted_div">containing my text</div>
any ideas?
I am not sure these are the "best" ways to go at it but they shoud work
1) Have the data be interpreted as XML instead of plain text:
dojo.require('dojox.xml.parser');
dojo.xhrPost({
//...
handleAs: 'xml',
//...
load: function(response_div){
//content should be xml now
result.innerHTML = dojox.xml.parser.textContent(response_div);
}
//...
})
2) Convert it to html and then process it
//create a thworwaway div with the respnse
var d = dojo.create('div', {innerHTML: response});
result.innerHTML = d.firstChild.innerHTML;
2.1) Use dojo.query instead of .firstChild if you need smore sofistication.
I prefer handle as JSON format :) , dojo have more utilities to access and to iterate the response.
dojo.xhrGet({
url : url,
handleAs : "json",
failOk : true, //Indicates whether a request should be allowed to fail
//(and therefore no console error message in the event of a failure)
timeout : 20000,
content: {//params},
load: function(){ // something },
preventCache: true,
error: function(error, ioargs) {
console.info("error function", ioargs);
var message = "";
console.info(ioargs.xhr.status, error);
//error process
},
handle: function(response, ioargs) {
var message = "";
console.info(ioargs.xhr.status, error);
switch (ioargs.xhr.status) {
case 200:
message = "Good request.";
break;
case 404:
message = "The page you requested was not found.";
break;
case 0:
message = "A network error occurred. Check that you are connected to the internet.";
break;
default:
message = "An unknown error occurred";
}
}
});