2
\$\begingroup\$

A made a shipping calculator, which consists of one field that is validated.

jsFiddle

HTML:

    <div class="container main-container" id="mainContainer">
      <h1>Калькулятор доставки</h1>
      <div class="content-container" id="contentContainer"></div>
    </div>

<script type="text/template" id="calculatorSubmitButtonTemplate">
  <div class="btn btn-default" id="calculatorSubmitButton">Рассчитать</div>
</script>


<script type="text/template" id="cityOfDepartureTemplate">
  <div class="panel panel-default">
    <div class="panel-body">
      <h2>Город отправления</h2>
      <div class="input-group">
        <input type="text" class="form-control" id="fldCityOfDeparture">
        <div id="errorMessageCityOfDeparture" class="help-block"></div>
      </div>
    </div>
  </div>
</script> 

CSS:

.not_valid{
    border: 1px solid red;
}

.valid{
    border: 1px solid #ccc;
}

JS:

window.APP = window.APP || {};

APP.CityOfDepartureModel = Backbone.Model.extend({
  defaults: {
    cityName: undefined
  }, 

  validate: function(attrs) {   
    var errorsArr = [];

    if($.trim(attrs.cityName).length == 0) { 
        errorsArr.push('Это поле не может быть пустым') 
    } else {
        if(isNaN(attrs.cityName) == false) { errorsArr.push('Это поле не может быть цифрой') };    
    };  

    if(errorsArr.length != 0) { return errorsArr };
  }  
});



APP.CalculatorView = Backbone.View.extend({  

  initialize: function() {  
    this.cityOfDepartureModel = new APP.CityOfDepartureModel();
    this.cityOfDepartureWidjet = new APP.CityOfDepartureView({model: this.cityOfDepartureModel});
    this.render();
  },    

  el: $('#contentContainer'),

  template: _.template($('#calculatorSubmitButtonTemplate').html()),

  render: function () {  
    this.$el.append(this.cityOfDepartureWidjet.render().el);
    this.$el.append(this.template());
    return this;
  },

  events:{
    'click #calculatorSubmitButton' : 'submit'
  },

  submit: function() {
    var cityName = $('#fldCityOfDeparture').val();

    this.cityOfDepartureModel.set({'cityName': cityName});

    if(this.cityOfDepartureModel.isValid()) {        
      this.cityOfDepartureWidjet.validMarkAdd();
    } else {      
      var errorMessagesArr = this.cityOfDepartureModel.validationError;
      this.cityOfDepartureWidjet.notValidMarkAdd(errorMessagesArr);
      this.cityOfDepartureModel.set({'cityName': undefined});
    };

    console.log('-----------------------');
    console.log('city dep: ', this.cityOfDepartureModel.get('cityName'));
  }

});



APP.CityOfDepartureView = Backbone.View.extend({  

  initialize: function() {  

  },    

  tagName: 'div',

  className: 'city_of_departure_container',

  id: 'cityOfDepartureContainer',

  template: _.template($('#cityOfDepartureTemplate').html()),

  render: function () {  
    this.$el.html(this.template());
    return this;
  },

  notValidMarkAdd: function(errorMessagesArr) {
    this.$el.find('#fldCityOfDeparture').removeClass('valid').addClass('not_valid');

    this.$el.find('#errorMessageCityOfDeparture').html('');
    for(key in errorMessagesArr) {
      this.$el.find('#errorMessageCityOfDeparture').append(errorMessagesArr[key] + '<br>');
    };    
  },

  validMarkAdd: function() {
    this.$el.find('#fldCityOfDeparture').removeClass('not_valid').addClass('valid');
    this.$el.find('#errorMessageCityOfDeparture').html('');
  }  

});




var app = new APP.CalculatorView();
\$\endgroup\$
4
  • \$\begingroup\$ I tried the fiddle but can't tell what it's supposed to do, since nothing happens when i fill in the field and I don't read russian. Could you explain what the feature is? It seems like it's something pretty simple, so you might want to consider if you really need to use backbone -- it may way more firepower than you need. \$\endgroup\$
    – Jonah
    Commented Apr 30, 2016 at 17:58
  • \$\begingroup\$ result output in console \$\endgroup\$
    – cyklop77
    Commented Apr 30, 2016 at 18:19
  • \$\begingroup\$ Ok so it checks if the field is a number or not, and outputs that. Is that all you're doing? Or is this extracted from a larger project? Because if that's all you're doing, you shouldn't be using a framework... \$\endgroup\$
    – Jonah
    Commented Apr 30, 2016 at 18:38
  • \$\begingroup\$ just this. I'm a beginner :) \$\endgroup\$
    – cyklop77
    Commented Apr 30, 2016 at 18:45

1 Answer 1

1
\$\begingroup\$

Getting rid of backbone, you can simplify this a lot.

HTML

<div class="container main-container" id="mainContainer">
  <h1>Калькулятор доставки</h1>
  <div class="content-container" id="contentContainer">
    <div class="panel panel-default">
      <div class="panel-body">
        <h2>Город отправления</h2>
        <div class="input-group">
          <input type="text" class="form-control" id="fldCityOfDeparture">
          <div id="errorMessageCityOfDeparture" class="help-block not_valid"></div>
        </div>
      </div>
    </div>
    <div class="btn btn-default" id="calculatorSubmitButton">Рассчитать</div>
  </div>
</div>

JS

function validate(city) {
    return city.length == 0     ? 'Это поле не может быть пустым' :
           isNaN(city) == false ? 'Это поле не может быть цифрой' : '';
}
function showError(error) {
  document.getElementById('errorMessageCityOfDeparture').innerHTML = error;
}
document.getElementById('calculatorSubmitButton').onclick = () => {
  var city = document.getElementById('fldCityOfDeparture').value,
      error = validate(city);
  showError(error);
};

Here's a new fiddle, which shows the error messages on the page, rather than in the console.

https://jsfiddle.net/5uygd9s1/

NOTE: Currently I'm only using the not_valid class, since the border will not display when the error is empty. If you want, you can change the class too depending on if there is an error or not. The important point is finding a simple solution, especially when the problem is simple. With all the available js frameworks today, it's easy to over-engineer.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.